package com.cloudkinto.service.ft.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.ali.AliOss;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.service.channel.LogisticsChannelService;
import com.cloudkinto.service.ft.FreightFarawaySurchargeService;
import com.cloudkinto.service.ft.FreightOverSurchargeService;
import com.cloudkinto.service.ft.FreightTempService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.zone.ZoneTempRuleService;
import com.cloudkinto.service.zone.ZoneTempService;
import com.cloudkinto.vo.channel.lc.LcChannelPageRes;
import com.cloudkinto.vo.ft.*;
import com.cloudkinto.vo.ft.importVo.FreightWeightImportRes;
import com.cloudkinto.vo.ft.surcharge.*;
import com.cloudkinto.vo.zone.ZoneTempRuleAddReq;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 物流费模板 service实现类
 * </p>
 *
 * @author hua
 * @since 2024-11-07
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FreightTempServiceImpl extends ServiceImpl<FreightTempDao, FreightTempDo> implements FreightTempService {
    @Autowired
    private FreightTempDao dao;
    @Autowired
    private ZoneTempRuleService zoneTempRuleService;
    @Autowired
    private FreightTempWeightDao freightTempWeightDao;
    @Autowired
    private FreightTempZonePriceDao freightTempZonePriceDao;
    @Autowired
    private ZoneTempService zoneTempService;
    @Value("${gbc.template.filePath}")
    private String templatePath;
    @Value("${gbc.template.localPath}")
    private String localPath;
    @Value("${gbc.uploadPath.filePathTemp}")
    private String filePathTemp;
    @Value("${gbc.uploadPath.filePath}")
    private String filePath;
    @Value("${gbc.uploadPath.fileUrl}")
    private String fileUrl;
    @Autowired
    private FreightFarawaySurchargeService freightFarawaySurchargeService;
    @Autowired
    private FreightFarawaySurchargeDao freightFarawaySurchargeDao;
    @Autowired
    private FreightOverSurchargeDao freightOverSurchargeDao;
    @Autowired
    private FreightOverSurchargeService freightOverSurchargeService;
    @Autowired
    private LogisticsChannelDao logisticsChannelDao;
    @Autowired
    private LogisticsChannelService logisticsChannelService;
    @Autowired
    private OperateRecordService operateRecordService;
    @Autowired
    private QuotationSchemeDao quotationSchemeDao;


    public void checkWeight(Set<String> zone, List<FreightTempWeightAddReq> weightList, int volumeWeightCalculateWay) {
        //三边和
        double end = 0;
        double endVol = 0d;
        for (FreightTempWeightAddReq weight : weightList) {
            Set<String> collect = weight.getZonePriceList().stream().map(FreightTempZonePriceAddReq::getZone).collect(Collectors.toSet());
            if (!collect.equals(zone)) throw new BizException(SysConstant.Freight_Weight_Zone_NotSame);
            if (weight.getStartWeight() != end) {
                throw new BizException(SysConstant.Freight_Weight_LianXU);
            }
            end = weight.getEndWeight();
            if (volumeWeightCalculateWay == 1) {
                if (weight.getStartVolumeWeight() != endVol) {
                    throw new BizException(SysConstant.Freight_Weight_LianXU);
                }
                endVol = weight.getEndVolumeWeight();

            }
        }
    }

    public void checkName(FreightTempEt addReq, Long id, String type, Long tenantId) {
        if (StringUtils.isBlank(addReq.getFreightTempName()))
            throw new BizException(SysConstant.ZoneTemp_Add_Name_Empty);
        //名称不能重复
        FreightTempDo et = dao.selectOne(new LambdaQueryWrapper<FreightTempDo>()
                .ne(id != null, FreightTempDo::getId, id)
                .eq(FreightTempDo::getFreightTempName, addReq.getFreightTempName())
                .eq(FreightTempDo::getType, type)
                .eq(FreightTempDo::getTenantId, tenantId));
        if (et != null) throw new BizException(SysConstant.ZoneTemp_Add_Name_Same);

    }

    public void checkZone(List<ZoneTempRuleAddReq> zoneList) {
        for (ZoneTempRuleAddReq rule : zoneList) {
            String s = zoneTempService.checkPostCode(rule.getStartPostCode(), rule.getEndPostCode());
            if (StringUtils.isNotBlank(s)) throw new BizException(s);
        }
    }


    @Override
    public Object addFreightTemp(FreightTempAddReq req, Long userId, Long tenantId) {
        return this.add(req, "freightTemp", null, userId, tenantId);
    }

    @Override
    public Object addFreight(FreightAddReq req, Long userId, Long tenantId) {
        if (req.getChannelId() == null) throw new BizException(SysConstant.No_Data);
        return this.add(req, "freight", req.getChannelId(), userId, tenantId);
    }

    public Object add(FreightTempAddReq req, String type, Long channelId, Long userId, Long tenantId) {
        this.checkName(req, null, type, tenantId);
        this.checkZone(req.getZoneList());
        Set<String> zone = req.getZoneList().stream().map(ZoneTempRuleAddReq::getZone).collect(Collectors.toSet());
        this.checkWeight(zone, req.getWeightList(), req.getVolumeWeightCalculateWay());
        FreightTempDo entityDo = new FreightTempDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCreateBy(userId);
        entityDo.setType(type);
        entityDo.setChannelId(channelId);
        dao.insert(entityDo);
        //插入分区
        zoneTempRuleService.update(req.getZoneList(), entityDo.getId(), type, userId);
        //插入重量段
        this.insertWeight(req.getWeightList(), entityDo.getId(), type, userId);
        //附加费
        if (req.getSc() != null) {
            if (req.getSc().getAddr() != null && req.getSc().getAddr().isSelected()) {
                FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(StaticDict.Surcharge_Faraway_type.ResidenceSeason.getValue(), req.getSc().getAddr().getCommonAddrFee(), type, entityDo.getId());
                freightFarawaySurchargeService.getBaseMapper().insert(addSc);
            }
            if (req.getSc().getInsurance() != null && req.getSc().getInsurance().isSelected()) {
                FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(StaticDict.Surcharge_Faraway_type.Insurance.getValue(), req.getSc().getInsurance().getCommonAddrFee(), type, entityDo.getId());
                freightFarawaySurchargeService.getBaseMapper().insert(addSc);
            }
            if (req.getSc().getSignList() != null && !req.getSc().getSignList().isEmpty()) {
                //签名
                for (FreightScSignAddReq signReq : req.getSc().getSignList()) {
                    if (!signReq.isSelected()) continue;
                    FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(signReq.getFarawayRuleType(), signReq.getCommonAddrFee(), type, entityDo.getId());
                    freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                }
            }
            if (req.getSc().getFarawayList() != null && !req.getSc().getFarawayList().isEmpty()) {
                for (FreightScFarawayAddReq farReq : req.getSc().getFarawayList()) {
                    if (!farReq.isSelected()) continue;
                    FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(farReq.getFarawayRuleType(), farReq.getCommonAddrFee(), farReq.getBusinessAddrFee(), farReq.getResidenceAddrFee(), farReq.getDistinctAddrType(), farReq.getFarawayRuleId(), type, entityDo.getId());
                    freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                }
            }
            if (req.getSc().getOverList() != null && !req.getSc().getOverList().isEmpty()) {
                for (FreightScOverAddReq overReq : req.getSc().getOverList()) {
                    if (!overReq.isSelected()) continue;
                    FreightOverSurchargeDo addSc = new FreightOverSurchargeDo(overReq.getSurchargeType(), overReq.getDistinctAddrType(), overReq.getOverId(), type, entityDo.getId());
                    freightOverSurchargeService.getBaseMapper().insert(addSc);
                    for (FreightScOverPriceAddReq zonePriceReq : overReq.getZonePriceList()) {
                        FreightTempZonePriceDo priceSc = new FreightTempZonePriceDo(zonePriceReq.getZone(), zonePriceReq.getZonePrice(), addSc.getId(), entityDo.getId(), zonePriceReq.getAddrType(), "surcharge");
                        freightTempZonePriceDao.insert(priceSc);
                    }

                }
            }
        }
        //操作日志
        operateRecordService.operateAddRecordAndValue("新建物流费", "", entityDo.getId(), userId, null, OperateTypeEnum.Freight);
        return entityDo.getId();
    }

    public void insertWeight(List<FreightTempWeightAddReq> weightList, Long id, String type, Long userId) {
        for (FreightTempWeightAddReq weight : weightList) {
            FreightTempWeightDo weightDo = BeanConvert.INSTANCE.freightTempWeightDo(weight);
            weightDo.setTempId(id);
            weightDo.setCreateBy(userId);
            weightDo.setWeightType(type);
            freightTempWeightDao.insert(weightDo);
            //插入分区价格
            for (FreightTempZonePriceAddReq price : weight.getZonePriceList()) {
                FreightTempZonePriceDo priceEt = BeanConvert.INSTANCE.freightTempZonePriceDo(price);
                priceEt.setFreightTempWeightId(weightDo.getId());
                priceEt.setPriceType(type);
                priceEt.setTempId(id);
                freightTempZonePriceDao.insert(priceEt);
            }
        }
    }

    @Override
    public Object updateFreightTemp(FreightTempUpdateReq req, Long userId, Long tenantId) {
        return this.update(req, null, userId, tenantId);
    }

    @Override
    public Object updateFreight(FreightUpdateReq req, Long userId, Long tenantId) {
        return this.update(req, req.getChannelId(), userId, tenantId);
    }


    public Object update(FreightTempUpdateReq req, Long channelId, Long userId, Long tenantId) {
        FreightTempDo entityDo = dao.selectById(req.getId());
        this.checkName(req, req.getId(), entityDo.getType(), tenantId);
        this.checkZone(req.getZoneList());
        Set<String> zone = req.getZoneList().stream().map(ZoneTempRuleAddReq::getZone).collect(Collectors.toSet());
        //三边和
        double end = 0;
        double endVol = 0d;
        for (FreightTempWeightAddReq weight : req.getWeightList()) {
            if (weight.getStartWeight() != end) {
                throw new BizException(SysConstant.Freight_Weight_LianXU);
            }
            Set<String> collect = weight.getZonePriceList().stream().map(FreightTempZonePriceAddReq::getZone).collect(Collectors.toSet());
            if (!collect.equals(zone)) throw new BizException(SysConstant.Freight_Weight_Zone_NotSame);
            end = weight.getEndWeight();
            if (req.getVolumeWeightCalculateWay() == 1) {
                if (weight.getStartVolumeWeight() != endVol) {
                    throw new BizException(SysConstant.Freight_Weight_LianXU);
                }
                endVol = weight.getEndVolumeWeight();

            }
        }
        if ("freight".equals(entityDo.getType())) {
            //判断仓租费有没有被使用过
            int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(req.getId(), 0, tenantId);
            if (qsItemTypeUseCount > 0) {
                if (!Objects.equals(req.getCurrencyCode(), entityDo.getCurrencyCode()))
                    throw new BizException(SysConstant.Freight_CurrencyCode_CannotEdit);
                req.setFreightTempName(entityDo.getFreightTempName());
            }
        }
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setUpdateBy(userId);
        entityDo.setChannelId(channelId);
        dao.updateById(entityDo);
        //插入分区
        zoneTempRuleService.update(req.getZoneList(), entityDo.getId(), entityDo.getType(), userId);
        //重量段价格
        List<FreightTempWeightDo> oldWeightList = freightTempWeightDao.selectList(new LambdaQueryWrapper<FreightTempWeightDo>().eq(FreightTempWeightDo::getTempId, entityDo.getId())
                .eq(FreightTempWeightDo::getWeightType, entityDo.getType()));
//        List<Long> oldWeightIds = oldWeightList.stream().map(FreightTempWeightDo::getId).collect(Collectors.toList());
        List<Long> newWeightIds = req.getWeightList().stream().map(FreightTempWeightUpdateReq::getId).filter(Objects::nonNull).collect(Collectors.toList());
        List<Long> deleteWeightIds = oldWeightList.stream().map(FreightTempWeightDo::getId).filter(i -> !newWeightIds.contains(i)).collect(Collectors.toList());

        List<Long> deletePriceWeightIds = req.getWeightList().stream().filter(i -> i.getId() != null && i.isEdit()).map(FreightTempWeightUpdateReq::getId).collect(Collectors.toList());
        deletePriceWeightIds.addAll(deleteWeightIds);
        //先删除编辑过的重量价格
        if (!deletePriceWeightIds.isEmpty())
            freightTempZonePriceDao.updateDelete(deletePriceWeightIds, entityDo.getType(), userId);
        //删除重量段
        if (!deleteWeightIds.isEmpty()) freightTempWeightDao.updateDelete(deleteWeightIds, entityDo.getType(), userId);
        for (FreightTempWeightUpdateReq weight : req.getWeightList()) {
            if (weight.getId() == null) {
                //插入
                this.insertWeight(Collections.singletonList(weight), entityDo.getId(), entityDo.getType(), userId);
            } else if (weight.isEdit()) { //是否编辑过
                FreightTempWeightDo weightDo = BeanConvert.INSTANCE.freightTempWeightDo(weight);
                weightDo.setUpdateBy(userId);
                freightTempWeightDao.updateById(weightDo);
                //插入子表
                for (FreightTempZonePriceAddReq price : weight.getZonePriceList()) {
                    FreightTempZonePriceDo priceEt = BeanConvert.INSTANCE.freightTempZonePriceDo(price);
                    priceEt.setFreightTempWeightId(weightDo.getId());
                    priceEt.setTempId(entityDo.getId());
                    priceEt.setPriceType(entityDo.getType());
                    freightTempZonePriceDao.insert(priceEt);
                }
            }
        }

        //附加费
        if (req.getSc() != null) {
            if (req.getSc().getAddr() != null) {
                if (req.getSc().getAddr().isSelected()) {
                    //修改过
                    FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(StaticDict.Surcharge_Faraway_type.ResidenceSeason.getValue(), req.getSc().getAddr().getCommonAddrFee(), entityDo.getType(), entityDo.getId());
                    if (req.getSc().getAddr().getTableId() == null) {
                        freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                    } else {
                        addSc.setId(req.getSc().getAddr().getTableId());
                        freightFarawaySurchargeService.getBaseMapper().updateById(addSc);
                    }
                } else {
                    //删除
                    if (req.getSc().getAddr().getTableId() != null)
                        freightFarawaySurchargeDao.updateDelete(req.getSc().getAddr().getTableId(), userId);
                }

            }
            if (req.getSc().getInsurance() != null) {
                if (req.getSc().getInsurance().isSelected()) {
                    FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(StaticDict.Surcharge_Faraway_type.Insurance.getValue(), req.getSc().getInsurance().getCommonAddrFee(), entityDo.getType(), entityDo.getId());
                    if (req.getSc().getInsurance().getTableId() == null) {
                        freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                    } else {
                        addSc.setId(req.getSc().getAddr().getTableId());
                        freightFarawaySurchargeService.getBaseMapper().updateById(addSc);
                    }
                } else if (req.getSc().getInsurance().getTableId() != null)
                    freightFarawaySurchargeDao.updateDelete(req.getSc().getInsurance().getTableId(), userId);
            }

            if (req.getSc().getSignList() != null && !req.getSc().getSignList().isEmpty()) {
                //签名
                for (FreightScSignUpdateReq signReq : req.getSc().getSignList()) {
                    if (signReq.isSelected()) {
                        FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(signReq.getFarawayRuleType(), signReq.getCommonAddrFee(), entityDo.getType(), entityDo.getId());
                        if (signReq.getTableId() == null) {
                            freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                        } else {
                            addSc.setId(signReq.getTableId());
                            freightFarawaySurchargeService.getBaseMapper().updateById(addSc);
                        }
                    } else if (signReq.getTableId() != null)
                        freightFarawaySurchargeDao.updateDelete(signReq.getTableId(), userId);
                }
            }
            if (req.getSc().getFarawayList() != null && !req.getSc().getFarawayList().isEmpty()) {
                for (FreightScFarawayUpdateReq signReq : req.getSc().getFarawayList()) {
                    if (signReq.isSelected()) {
                        FreightFarawaySurchargeDo addSc = new FreightFarawaySurchargeDo(signReq.getFarawayRuleType(), signReq.getCommonAddrFee(), signReq.getFarawayRuleId(), entityDo.getType(), entityDo.getId());
                        if (signReq.getTableId() == null) {
                            freightFarawaySurchargeService.getBaseMapper().insert(addSc);
                        } else {
                            addSc.setId(signReq.getTableId());
                            freightFarawaySurchargeService.getBaseMapper().updateById(addSc);
                        }
                    } else if (signReq.getTableId() != null)
                        freightFarawaySurchargeDao.updateDelete(signReq.getTableId(), userId);
                }
            }
            if (req.getSc().getOverList() != null && !req.getSc().getOverList().isEmpty()) {
                for (FreightScOverUpdateReq overReq : req.getSc().getOverList()) {
                    if (overReq.isSelected()) {
                        FreightOverSurchargeDo addSc = new FreightOverSurchargeDo(overReq.getSurchargeType(), overReq.getDistinctAddrType(), overReq.getOverId(), entityDo.getType(), entityDo.getId());
                        if (overReq.getTableId() == null) {
                            freightOverSurchargeService.getBaseMapper().insert(addSc);
                        } else {
                            addSc.setId(overReq.getTableId());
                            freightOverSurchargeService.getBaseMapper().updateById(addSc);
                        }
                        //删除
                        freightTempZonePriceDao.updateDeleteByThirdId(addSc.getId(), "surcharge", userId);
                        for (FreightScOverPriceAddReq zonePriceReq : overReq.getZonePriceList()) {
                            FreightTempZonePriceDo priceSc = new FreightTempZonePriceDo(zonePriceReq.getZone(), zonePriceReq.getZonePrice(), addSc.getId(), entityDo.getId(), zonePriceReq.getAddrType(), "surcharge");
                            freightTempZonePriceDao.insert(priceSc);
                        }

                    } else if (overReq.getTableId() != null) {
                        freightOverSurchargeDao.updateDelete(overReq.getTableId(), userId);
                        freightTempZonePriceDao.updateDeleteByThirdId(overReq.getTableId(), "surcharge", userId);
                    }
                }
            }
        }
        operateRecordService.operateAddRecordAndValue("更新物流费", "", entityDo.getId(), userId, null, OperateTypeEnum.Freight);

        return entityDo.getId();
    }

    @Override
    public int delete(Long id, Long userId, Long tenantId) {
        FreightTempDo entityDo = dao.selectById(id);
        if (entityDo == null) return 0;
        if (!Objects.equals(entityDo.getTenantId(), tenantId)) return 0;
        if ("freight".equals(entityDo.getType())) {
            int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(id, 0, tenantId);
            if (qsItemTypeUseCount > 0) {
                throw new BizException(SysConstant.Freight_Status_CannotEdit);
            }
        }
        int i = dao.updateDelete(id, userId, tenantId);
        if (i > 0) {
            //删除子表
            freightTempWeightDao.updateDeleteByTempId(id, "freightTemp", userId);
            freightTempZonePriceDao.updateDeleteByTempId(id, "freightTemp", userId);
            freightFarawaySurchargeDao.updateDeleteByFreightId(id, userId);
            freightOverSurchargeDao.updateDeleteByFreightId(id, userId);
            //删除zonePrice
            freightTempZonePriceDao.updateDeleteByTempId(id, "surcharge", userId);
        }
        return i;
    }

    @Override
    public FreightTempDetailRes detail(Long id) {
        FreightTempDo entityDo = dao.selectById(id);
        FreightTempDetailRes res = new FreightTempDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        //物流渠道名称
        if ("freight".equals(entityDo.getType())) {
            LogisticsChannelDo channelDo = logisticsChannelDao.selectById(entityDo.getChannelId());
            if (channelDo != null) res.setChannelName(channelDo.getChannelName());
        }

        //获取分区规则列表
        List<ZoneTempRuleDo> list = zoneTempRuleService.list(new LambdaQueryWrapper<ZoneTempRuleDo>().eq(ZoneTempRuleDo::getTempId, id)
                .eq(ZoneTempRuleDo::getZoneType, entityDo.getType()));
        List<ZoneTempRuleAddReq> zoneList = new ArrayList<>();
        for (ZoneTempRuleDo e : list) {
            ZoneTempRuleAddReq req = new ZoneTempRuleAddReq();
            BeanUtils.copyProperties(e, req);
            zoneList.add(req);
        }
        res.setZoneList(zoneList);
        //重量段
        List<FreightTempWeightDo> weightDoList = freightTempWeightDao.selectList(new LambdaQueryWrapper<FreightTempWeightDo>().eq(FreightTempWeightDo::getTempId, id)
                .eq(FreightTempWeightDo::getWeightType, entityDo.getType()));
        List<FreightTempWeightUpdateReq> weightList = BeanConvert.INSTANCE.freightTempWeightUpdateReq(weightDoList);
        if (!weightDoList.isEmpty()) {
            List<FreightTempZonePriceDo> priceDos = freightTempZonePriceDao.selectList(new LambdaQueryWrapper<FreightTempZonePriceDo>()
                    .in(FreightTempZonePriceDo::getFreightTempWeightId, weightDoList.stream().map(FreightTempWeightDo::getId).collect(Collectors.toList()))
                    .eq(FreightTempZonePriceDo::getPriceType, entityDo.getType()));
            Map<Long, List<FreightTempZonePriceDo>> collect = priceDos.stream().collect(Collectors.groupingBy(FreightTempZonePriceDo::getFreightTempWeightId));
            for (FreightTempWeightUpdateReq tempWeightUpdateReq : weightList) {
                List<FreightTempZonePriceAddReq> priceAddReqList = BeanConvert.INSTANCE.freightTempZonePriceAddReq(collect.get(tempWeightUpdateReq.getId()));
                tempWeightUpdateReq.setZonePriceList(priceAddReqList);
            }
        }
        res.setWeightList(weightList);
        //偏远地区
        Map<Integer, List<FreightFarawaySurchargeDo>> farawayC = freightFarawaySurchargeService.getFarawaySc(entityDo.getType(), id).stream().collect(Collectors.groupingBy(FreightFarawaySurchargeDo::getFarawayRuleType));
        //超长超重附加费
        Map<Integer, List<FreightOverScEt>> overC = freightOverSurchargeService.getOverScList(entityDo.getType(), id).stream().collect(Collectors.groupingBy(FreightOverScEt::getSurchargeType));
        List<FreightScFarawayUpdateReq> farawayList = new ArrayList<>();
        FreightScAddrUpdateReq addr = new FreightScAddrUpdateReq();
        List<FreightScSignUpdateReq> signList = new ArrayList<>();
        FreightScAddrUpdateReq insurance = new FreightScAddrUpdateReq();
        for (StaticDict.Surcharge_Faraway_type value : StaticDict.Surcharge_Faraway_type.values()) {
            List<FreightFarawaySurchargeDo> scList = farawayC.get(value.getValue());
            if ("faraway".equals(value.getType())) {
                if (scList == null || scList.isEmpty()) {
                    FreightScFarawayUpdateReq u = new FreightScFarawayUpdateReq();
                    u.setFarawayRuleType(value.getValue());
                    farawayList.add(u);
                } else {
                    FreightScFarawayUpdateReq copy = BeanConvert.INSTANCE.freightScFarawayUpdateReq(scList.get(0));
                    copy.setSelected(true);
                    farawayList.add(copy);
                }
            } else if ("residence".equals(value.getType())) {//住宅地址附加费
                if (scList == null || scList.isEmpty()) {
                    addr.setSelected(false);
                } else {
                    addr.setSelected(true);
                    addr.setTableId(scList.get(0).getId());
                    addr.setCommonAddrFee(scList.get(0).getCommonAddrFee());
                }
            } else if ("insurance".equals(value.getType())) {
                if (scList == null || scList.isEmpty()) {
                    insurance.setSelected(false);
                } else {
                    insurance.setSelected(true);
                    insurance.setTableId(scList.get(0).getId());
                    insurance.setCommonAddrFee(scList.get(0).getCommonAddrFee());
                }
            } else {
                //签名附加费
                if (scList == null || scList.isEmpty()) {
                    FreightScSignUpdateReq u = new FreightScSignUpdateReq();
                    u.setFarawayRuleType(value.getValue());
                    signList.add(u);
                } else {
                    FreightScSignUpdateReq copy = BeanConvert.INSTANCE.freightScSignUpdateReq(scList.get(0));
                    copy.setSelected(true);
                    signList.add(copy);
                }
            }
        }
        List<FreightScOverUpdateReq> overList = new ArrayList<>();
        for (StaticDict.Surcharge_type value : StaticDict.Surcharge_type.values()) {
            List<FreightOverScEt> scList = overC.get(value.getValue());
            FreightScOverUpdateReq u;
            if (scList == null || scList.isEmpty()) {
                u = new FreightScOverUpdateReq();
                u.setSurchargeType(value.getValue());
            } else {
                u = BeanConvert.INSTANCE.freightScOverUpdateReq(scList.get(0));
                u.setSelected(true);
            }
            overList.add(u);
        }

        FreightScUpdateReq sc = new FreightScUpdateReq(farawayList, addr, signList, insurance, overList);
        res.setSc(sc);

        res.setOperateResList(operateRecordService.getOperateList(id, OperateTypeEnum.Freight));

        return res;
    }


    @Override
    public SingleResult pageInit() {
        Map<String, Object> result = new HashMap<>();
        result.put("unit", StaticDict.getUnitMeasure());
        List<Map<String, Object>> scType = new ArrayList<>();
        for (StaticDict.Surcharge_Faraway_type value : StaticDict.Surcharge_Faraway_type.values()) {
            if (!"faraway".equals(value.getType())) continue;
            Map<String, Object> map = new HashMap<>();
            map.put("id", value.getValue());
            map.put("name", value.getText());
            map.put("type", value.getType());
            scType.add(map);
        }
        for (StaticDict.Surcharge_type value : StaticDict.Surcharge_type.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", value.getValue());
            map.put("name", value.getText());
            map.put("type", "over");
            scType.add(map);
        }

        for (StaticDict.Surcharge_Faraway_type value : StaticDict.Surcharge_Faraway_type.values()) {
            if ("faraway".equals(value.getType()) || "signature".equals(value.getType())) continue;
            Map<String, Object> map = new HashMap<>();
            map.put("id", value.getValue());
            map.put("name", value.getText());
            map.put("type", value.getType());
            scType.add(map);
        }
        Map<String, Object> signature = new HashMap<>();
        signature.put("id", Arrays.asList(StaticDict.Surcharge_Faraway_type.Signature_Direct.getValue(), StaticDict.Surcharge_Faraway_type.Signature_Indirect.getValue(), StaticDict.Surcharge_Faraway_type.Signature_Adult.getValue()));
        signature.put("name", "签名附加费");
        signature.put("type", "signature");
        scType.add(signature);

        result.put("scType", scType);

        return SingleResult.success(result);
    }

    @Override
    public List<FreightTempPageVo> getList(Map<String, Object> map) {
        return dao.list(map);
    }

    @Override
    public PageResult getListPage(Map<String, Object> map) {
        IPage<FreightTempPageVo> page = pageInitDto(map);
        page = dao.list(page, map);
        PageResult result = new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private IPage<FreightTempPageVo> pageInitDto(Map<String, Object> map) {
        IPage<FreightTempPageVo> page = new Page<>();
        page.setSize(map.get("pageSize") != null ? Long.parseLong(map.get("pageSize").toString()) : 10);
        page.setCurrent(map.get("current") != null ? Long.parseLong(map.get("current").toString()) : 1);
        return page;
    }

    @Override
    public void getFullTemplate(Integer volumeWeightCalculateWay, String zone, HttpServletResponse response) {
        if (volumeWeightCalculateWay == null) throw new BizException(SysConstant.No_Data);
        if (StringUtils.isBlank(zone)) throw new BizException(SysConstant.Freight_GetTemplate_Zone_Empty);
        String templateName = (volumeWeightCalculateWay == 1 ? "Weight_Zone_Rates_Import_For_Trilateral_Sum" : "Weight_Zone_Rates_Import");
        TemplateExportParams params = new TemplateExportParams(localPath + templateName + ".xlsx");
        if (volumeWeightCalculateWay != 1) {
            params.setSheetNum(new Integer[]{0, 1, 2});
        }
        Workbook workbook = ExcelExportUtil.exportExcel(params, new HashMap<>());
        if (volumeWeightCalculateWay != 1) {
            //第一页表头渲染
            for (int s = 0; s < 2; s++) {
                Sheet sheet0 = workbook.getSheetAt(s);
                Row row0 = sheet0.getRow(0);
                CellStyle cellStyle = row0.getCell(s == 0 ? 1 : 3).getCellStyle();
                //渲染第一行表头的分区
                for (int i = 0; i < zone.split(",").length; i++) {
                    Cell cell = row0.getCell(i + (s == 0 ? 1 : 3));
                    if (cell == null) cell = row0.createCell(i + (s == 0 ? 1 : 3));
                    cell.setCellValue(zone.split(",")[i]);
                    cell.setCellStyle(cellStyle);
                }
            }
        } else {
            //三边和渲染
            Sheet sheet0 = workbook.getSheetAt(0);
            Row row0 = sheet0.getRow(0);
            CellStyle cellStyle = row0.getCell(2).getCellStyle();
            //渲染第一行表头的分区
            for (int i = 0; i < zone.split(",").length; i++) {
                Cell cell = row0.getCell(i + (2));
                if (cell == null) cell = row0.createCell(i + (2));
                cell.setCellValue(zone.split(",")[i]);
                cell.setCellStyle(cellStyle);
            }
        }

        try {
            ExcelUtils.downLoadExcel(templateName, response, workbook);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


//        templateName += ".xlsx";
//        String filePathLocal = filePathTemp;
//        File fileDo = new File(filePathLocal);
//        if (!fileDo.exists()) {
//            fileDo.mkdirs();
//        }
//        filePathLocal += File.separator + templateName;
//        OutputStream outputStream = null;
//        try {
//            outputStream = new FileOutputStream(filePathLocal);
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
//        //先保存到临时路径，在通过文件上传的方法上传到正式路径
//        try {
//            workbook.write(outputStream);
//            workbook.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        CompanyImportRes res = new CompanyImportRes();
//        String objectNameTemporary = "";
//        if (filePath.startsWith("http")) {
//            try {
//                objectNameTemporary = AliOss.temporaryFile2(templateName, new File(filePathLocal));
//            } catch (Exception e) {
//                e.printStackTrace();
//                log.error("导出文件失败" + e.getMessage());
//            }
//            res.setFailFileUrl(fileUrl + objectNameTemporary);
//        }
//        else {
//            res.setFailFileUrl(fileUrl + templateName);
//        }

    }


    @Override
    public FreightWeightImportRes importT(MultipartFile file, Integer volumeWeightCalculateWay, String zone) {
        String[] zoneSplit = zone.split(",");
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) && !GlobalConstants.IMG_TYPE_CSV.equals(suffix.toUpperCase())
                && !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizException(SysConstant.File_Form_Incorrect);
        }

        XSSFWorkbook xssfWorkbook = null;
        try {
            xssfWorkbook = new XSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        List<FreightTempWeightAddReq> weightList = new ArrayList<>();
        if (volumeWeightCalculateWay == 1) {
            int zoneIndex = 2;
            boolean err = false;
            String bigError = "";
            List<String> errors = new ArrayList<>();
            String[][] arr0 = this.getArrBySheet(xssfWorkbook, zoneSplit, 0, zoneIndex);
            List<String> zoneImportList = new ArrayList<>();//获取excel中分区  和前端传的是否一致
            for (int j = zoneIndex; j < arr0[0].length; j++) {
                if (!zoneImportList.contains(arr0[0][j])) zoneImportList.add(arr0[0][j]);
            }
            if (!zone.equals(StringUtils.join(zoneImportList, ","))) {
                bigError = ("分区不一致");
            } else {
                //三边和 就一个sheet
                for (int i = 1; i < arr0.length; i++) {
//                    boolean nullFlag = true;
//                    for (int j = 0; j < arr0[i].length; j++) {
//                        if (arr0[i][j] != null) {
//                            nullFlag = false;
//                            break;
//                        }
//                    }
//                    if (nullFlag) continue;
                    //校验分区
                    for (int j = 0; j < arr0[i].length; j++) {
                        if (StringUtils.isBlank(arr0[i][j]) || !arr0[i][j].matches("\\d+(\\.\\d+)?$")) {
                            errors.add("重量和价格必须要数字");
                            err = true;
                            break;
                        }
                        if (j == arr0[i].length - 1) {
                            errors.add("success");
                        }
                    }
                    for (int j = 0; j < arr0[i].length; j++) {
                        if (StringUtils.isBlank(bigError) && j < zoneIndex) {
                            //校验开始 结束
                            if (i == 1) continue;
                            if (Double.parseDouble(arr0[i][j]) <= Double.parseDouble(arr0[i - 1][j])) {
                                bigError = ("体积重或者重量 段不连续");
                                break;
                            }
                        }
                    }
                }
            }
            if (StringUtils.isBlank(bigError) && !err) {
                weightList.addAll(this.getWeightAddReq(arr0, volumeWeightCalculateWay, zoneIndex));
                FreightWeightImportRes res = new FreightWeightImportRes();
                res.setHeadList(Arrays.asList(zoneSplit));
                res.setSuccessList(weightList);
                res.setSuccessNum(weightList.size());
                return res;
            } else {
                String templateName = "Error_Weight_Zone_Rates_Import_For_Trilateral_Sum";
                TemplateExportParams params = new TemplateExportParams(localPath + templateName + ".xlsx");
                Workbook workbook = ExcelExportUtil.exportExcel(params, new HashMap<>());
                //三边和渲染
                Sheet sheet0 = workbook.getSheetAt(0);

                for (int i = 0; i < arr0.length; i++) {
                    Row row0 = sheet0.getRow(i);
                    if (row0 == null) row0 = sheet0.createRow(i);
                    if (i > 0 && errors.size() > i - 1) {
                        //第一列错误
                        Cell first = row0.getCell(0);
                        if (first == null) first = row0.createCell(0);
                        CellStyle firstStyle = sheet0.getRow(1).getCell(0).getCellStyle();
                        String e = errors.get(i - 1);
                        if (!"success".equals(e)) {
                            first.setCellValue(e);
                            first.setCellStyle(firstStyle);
                        }
                    }
                    for (int j = 0; j < arr0[i].length; j++) {
                        Cell cell = row0.getCell(j + 1);
                        if (cell == null) cell = row0.createCell(j + 1);
                        if (i == 0 && j >= 2) {
                            CellStyle cellStyle = row0.getCell(zoneIndex + 1).getCellStyle();
                            //表头 分区
                            if (StringUtils.isNotBlank(arr0[i][j])) {
                                cell.setCellValue(arr0[i][j]);
                                cell.setCellStyle(cellStyle);
                            }
                        } else if (i > 0) {
                            //渲染表格内容
                            CellStyle cellStyle = row0.getCell(j + 1).getCellStyle();
                            cell.setCellValue(arr0[i][j]);
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }

                if (StringUtils.isNotBlank(bigError)) {
                    Row row0 = sheet0.getRow(arr0.length);
                    Cell cell = row0.getCell(0);
                    if (cell == null) cell = row0.createCell(0);
                    CellStyle cellStyle = sheet0.getRow(1).getCell(0).getCellStyle();
                    cellStyle.setWrapText(false);
                    cell.setCellValue(bigError);
                    cell.setCellStyle(cellStyle);
                }

                String filePathLocal = filePathTemp;
                File fileDo = new File(filePathLocal);
                if (!fileDo.exists()) {
                    fileDo.mkdirs();
                }
                filePathLocal += File.separator + templateName + ".xlsx";
                OutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(filePathLocal);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                //先保存到临时路径，在通过文件上传的方法上传到正式路径
                try {
                    workbook.write(outputStream);
                    workbook.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                FreightWeightImportRes res = new FreightWeightImportRes();
                String objectNameTemporary = "";
                if (filePath.startsWith("http")) {
                    try {
                        objectNameTemporary = AliOss.temporaryFile2(templateName + ".xlsx", new File(filePathLocal));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("导出文件失败" + e.getMessage());
                    }
                    res.setFailFileUrl(fileUrl + objectNameTemporary);
                } else {
                    res.setFailFileUrl(fileUrl + templateName + ".xlsx");
                }
                res.setFileName(templateName + ".xlsx");
                res.setFailNum(arr0.length - 1);
                res.setSuccessNum(0);

                return res;
            }
        } else {
            int zoneIndex0 = 1;
            int zoneIndex1 = 3;
            boolean err0 = false;
            List<String> errors0 = new ArrayList<>();
            String bigError0 = "";

            String[][] arr0 = this.getArrBySheet(xssfWorkbook, zoneSplit, 0, zoneIndex0);
            String[][] arr1 = this.getArrBySheet(xssfWorkbook, zoneSplit, 1, zoneIndex1);
            List<String> zoneImportList = new ArrayList<>();//获取excel中分区  和前端传的是否一致
            for (int j = zoneIndex0; j < arr0[0].length; j++) {
                if (!zoneImportList.contains(arr0[0][j])) zoneImportList.add(arr0[0][j]);
            }
            if (!zone.equals(StringUtils.join(zoneImportList, ","))) {
                bigError0 = ("分区不一致");
            } else {
                //三边和 就一个sheet
                for (int i = 1; i < arr0.length; i++) {
                    //校验分区
                    for (int j = 0; j < arr0[i].length; j++) {
                        if (StringUtils.isBlank(arr0[i][j]) || !arr0[i][j].matches("\\d+(\\.\\d+)?$")) {
                            errors0.add("重量和价格必须要数字");
                            err0 = true;
                            break;
                        }
                        if (j == arr0[i].length - 1) {
                            errors0.add("success");
                        }
                    }
                    for (int j = 0; j < arr0[i].length; j++) {
                        if (StringUtils.isBlank(bigError0) && j < zoneIndex0) {
                            //校验开始 结束
                            if (i == 1) continue;
                            if (Double.parseDouble(arr0[i][j]) <= Double.parseDouble(arr0[i - 1][j])) {
                                bigError0 = ("重量段不连续");
                                break;
                            }
                        }
                    }
                }
            }

            boolean err1 = false;
            List<String> errors1 = new ArrayList<>();
            String bigError1 = "";
            zoneImportList.clear();
            for (int j = zoneIndex1; j < arr1[0].length; j++) {
                if (!zoneImportList.contains(arr1[0][j])) zoneImportList.add(arr1[0][j]);
            }
            if (!zone.equals(StringUtils.join(zoneImportList, ","))) {
                bigError1 = ("分区不一致");
            } else {
                //三边和 就一个sheet
                for (int i = 1; i < arr1.length; i++) {
                    //校验分区
                    for (int j = 0; j < arr1[i].length; j++) {
                        if (j == 1) {
                            if (!"续重价".equals(arr1[i][j]) && !"单价".equals(arr1[i][j])) {
                                errors1.add("计费模式 只有 续重价 和 单价");
                                err1 = true;
                                break;
                            }
                        } else {
                            if (StringUtils.isBlank(arr1[i][j]) || !arr1[i][j].matches("\\d+(\\.\\d+)?$")) {
                                errors1.add("重量和价格必须要数字");
                                err1 = true;
                                break;
                            }
                        }
                        if (j == arr1[i].length - 1) {
                            errors1.add("success");
                        }
                    }
                    for (int j = 0; j < arr1[i].length; j++) {
                        if (StringUtils.isBlank(bigError1) && j < 1) {//重量段只取第一列
                            //校验开始 结束
                            if (i == 1) continue;
                            if (Double.parseDouble(arr1[i][j]) <= Double.parseDouble(arr1[i - 1][j])) {
                                bigError1 = ("重量段不连续");
                                break;
                            }
                        }
                    }
                }
            }
            if (StringUtils.isBlank(bigError0) && !err0 && StringUtils.isBlank(bigError1) && !err1) {
                weightList.addAll(this.getWeightAddReq(arr0, volumeWeightCalculateWay, 1));
                List<FreightTempWeightAddReq> xuZhongWeightList = this.getWeightAddReq(arr1, volumeWeightCalculateWay, 3);
                if (!xuZhongWeightList.isEmpty() && !weightList.isEmpty())
                    xuZhongWeightList.get(0).setStartWeight(weightList.get(weightList.size() - 1).getEndWeight());
                weightList.addAll(xuZhongWeightList);
                FreightWeightImportRes res = new FreightWeightImportRes();
                res.setHeadList(Arrays.asList(zoneSplit));
                res.setSuccessList(weightList);
                res.setSuccessNum(weightList.size());
                return res;
            } else {
                //错误的情况
                String templateName = "Error_Weight_Zone_Rates_Import";
                TemplateExportParams params = new TemplateExportParams(localPath + templateName + ".xlsx");
                params.setSheetNum(new Integer[]{0, 1, 2});
                Workbook workbook = ExcelExportUtil.exportExcel(params, new HashMap<>());
                //三边和渲染
                Sheet sheet0 = workbook.getSheetAt(0);
                for (int i = 0; i < arr0.length; i++) {
                    Row row0 = sheet0.getRow(i);
                    if (row0 == null) row0 = sheet0.createRow(i);
                    if (i > 0 && errors0.size() > i - 1) {
                        //第一列错误
                        Cell first = row0.getCell(0);
                        if (first == null) first = row0.createCell(0);
                        CellStyle firstStyle = sheet0.getRow(1).getCell(0).getCellStyle();
                        String e = errors0.get(i - 1);
                        if (!"success".equals(e)) {
                            first.setCellValue(e);
                            first.setCellStyle(firstStyle);
                        }
                    }
                    for (int j = 0; j < arr0[i].length; j++) {
                        Cell cell = row0.getCell(j + 1);
                        if (cell == null) cell = row0.createCell(j + 1);
                        if (i == 0 && j >= zoneIndex0) {
                            CellStyle cellStyle = row0.getCell(zoneIndex0 + 1).getCellStyle();
                            //表头 分区
                            if (StringUtils.isNotBlank(arr0[i][j])) {
                                cell.setCellValue(arr0[i][j]);
                                cell.setCellStyle(cellStyle);
                            }
                        } else if (i > 0) {
                            //渲染表格内容
                            CellStyle cellStyle = sheet0.getRow(1).getCell(j + 1).getCellStyle();
                            cell.setCellValue(arr0[i][j]);
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }

                if (StringUtils.isNotBlank(bigError0)) {
                    Row row0 = sheet0.getRow(arr0.length);
                    Cell cell = row0.getCell(0);
                    if (cell == null) cell = row0.createCell(0);
                    CellStyle cellStyle = sheet0.getRow(1).getCell(0).getCellStyle();
                    cellStyle.setWrapText(false);
                    cell.setCellValue(bigError0);
                    cell.setCellStyle(cellStyle);
                }


                Sheet sheet1 = workbook.getSheetAt(1);
                for (int i = 0; i < arr1.length; i++) {
                    Row row0 = sheet1.getRow(i);
                    if (row0 == null) row0 = sheet1.createRow(i);
                    if (i > 0 && errors1.size() > i - 1) {
                        //第一列错误
                        Cell first = row0.getCell(0);
                        if (first == null) first = row0.createCell(0);
                        CellStyle firstStyle = sheet1.getRow(1).getCell(0).getCellStyle();
                        String e = errors1.get(i - 1);
                        if (!"success".equals(e)) {
                            first.setCellValue(e);
                            first.setCellStyle(firstStyle);
                        }
                    }
                    for (int j = 0; j < arr1[i].length; j++) {
                        Cell cell = row0.getCell(j + 1);
                        if (cell == null) cell = row0.createCell(j + 1);
                        if (i == 0 && j >= zoneIndex1) {
                            CellStyle cellStyle = row0.getCell(zoneIndex1 + 1).getCellStyle();
                            //表头 分区
                            if (StringUtils.isNotBlank(arr1[i][j])) {
                                cell.setCellValue(arr1[i][j]);
                                cell.setCellStyle(cellStyle);
                            }
                        } else if (i > 0) {
                            //渲染表格内容
                            CellStyle cellStyle = sheet1.getRow(1).getCell(j + 1).getCellStyle();
                            cell.setCellValue(arr1[i][j]);
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }

                if (StringUtils.isNotBlank(bigError1)) {
                    Row row0 = sheet1.getRow(arr1.length);
                    Cell cell = row0.getCell(0);
                    if (cell == null) cell = row0.createCell(0);
                    CellStyle cellStyle = sheet1.getRow(1).getCell(0).getCellStyle();
                    cellStyle.setWrapText(false);
                    cell.setCellValue(bigError1);
                    cell.setCellStyle(cellStyle);
                }

                String filePathLocal = filePathTemp;
                File fileDo = new File(filePathLocal);
                if (!fileDo.exists()) {
                    fileDo.mkdirs();
                }
                filePathLocal += File.separator + templateName + ".xlsx";
                OutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(filePathLocal);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                //先保存到临时路径，在通过文件上传的方法上传到正式路径
                try {
                    workbook.write(outputStream);
                    workbook.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                FreightWeightImportRes res = new FreightWeightImportRes();
                String objectNameTemporary = "";
                if (filePath.startsWith("http")) {
                    try {
                        objectNameTemporary = AliOss.temporaryFile2(templateName + ".xlsx", new File(filePathLocal));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("导出文件失败" + e.getMessage());
                    }
                    res.setFailFileUrl(fileUrl + objectNameTemporary);
                } else {
                    res.setFailFileUrl(fileUrl + templateName + ".xlsx");
                }
                res.setFileName(templateName + ".xlsx");
                res.setFailNum(arr0.length - 1);
                res.setSuccessNum(0);

                return res;

            }
        }
    }

    /**
     * @param xssfWorkbook
     * @param zoneSplit
     * @param zoneIndex    分区在excel中 开始的列 从1 开始
     */
    public String[][] getArrBySheet(XSSFWorkbook xssfWorkbook, String[] zoneSplit, int sheetAt, int zoneIndex) {
        //第二页
        XSSFSheet sheet1 = xssfWorkbook.getSheetAt(sheetAt);
        if (sheet1.getRow(0).getLastCellNum() > zoneSplit.length + zoneIndex)
            throw new BizException(SysConstant.Freight_WeightImport_ZoneError);
        String[][] arr = new String[sheet1.getLastRowNum()][zoneSplit.length + zoneIndex];

        int index = -1;
        for (int i = 0; i < sheet1.getLastRowNum(); i++) {
            XSSFRow row = sheet1.getRow(i);
            if (row == null) row = sheet1.createRow(i);
            boolean nullFlag = true;
            for (int j = 0; j < zoneSplit.length + zoneIndex; j++) {
                XSSFCell cell = row.getCell(j);
                if (cell == null) {
                    arr[i][j] = "";
                } else {
                    cell.setCellType(CellType.STRING);
                    arr[i][j] = cell.getStringCellValue();
                }
                if (StringUtils.isNotBlank(arr[i][j])) {
                    nullFlag = false;
                }
            }
            if (nullFlag) {
                index = i;
                break;
            }

        }
        if (index == -1) return arr;
        String[][] newArr = new String[index][zoneSplit.length + zoneIndex];
        for (int i = 0; i < newArr.length; i++) {
            System.arraycopy(arr[i], 0, newArr[i], 0, newArr[i].length);
        }
        return newArr;
    }

    public List<FreightTempWeightAddReq> getWeightAddReq(String[][] arr, Integer volWeiCalWay, int zoneIndex) {
        List<FreightTempWeightAddReq> weightList = new ArrayList<>();
        double startWeight = 0d, startVolWeight = 0d;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i][0] == null) break;
            //三边和(volWeiCalWay = 1) 只有总价,当其他的时候 通过 zoneIndex 判断是 sheet1 还是sheet2, sheet2 取第一行 第二列 判断计费模式 续重价还是单价
            FreightTempWeightAddReq weight = volWeiCalWay == 1 ? new FreightTempWeightAddReq(startVolWeight, Double.parseDouble(arr[i][0]), startWeight, Double.parseDouble(arr[i][1]), 0)
                    : new FreightTempWeightAddReq(startWeight, Double.parseDouble(arr[i][0]), zoneIndex == 1 ? 0 : ("续重价".equals(arr[i][1]) ? 1 : 2));
            startWeight = weight.getEndWeight();
            startVolWeight = weight.getEndVolumeWeight();
            //价格
            List<FreightTempZonePriceAddReq> zonePriceList = new ArrayList<>();
            for (int j = zoneIndex; j < arr[i].length; j++) {
                zonePriceList.add(new FreightTempZonePriceAddReq(Double.parseDouble(arr[i][j]), arr[0][j]));
            }
            weight.setZonePriceList(zonePriceList);
            weightList.add(weight);
        }
        return weightList;
    }

    @Override
    public List<LcChannelPageRes> getChannelList(Long tenantId) {
        Map<String, Object> map = new HashMap<>();
        map.put("bindWarehouseQuantity", 1);
        map.put("tenantId", tenantId);
        List<LcChannelPageRes> list = logisticsChannelService.getList(map);
        return list;
    }

    @Override
    public void updateStatus(FreightStatusUpdateReq req, Long userId, Long tenantId) {
        FreightTempDo et = dao.selectById(req.getId());
        if (et == null) return;
        if (et.getStatus() == req.getStatus()) return;
        if (!"freight".equals(et.getType())) return;
        //判断仓租费有没有被使用过
        int qsItemTypeUseCount = quotationSchemeDao.getQsItemTypeUseCount(req.getId(), 0, tenantId);
        if (qsItemTypeUseCount > 0) {
            throw new BizException(SysConstant.Freight_Status_CannotEdit);
        }
        et.setStatus(req.getStatus());
        dao.updateById(et);
        operateRecordService.operateAddRecordAndValue(req.getStatus() == 0 ? "启动物流费" : "停用物流费", "", et.getId(), userId, null, OperateTypeEnum.Freight);
    }

}
